import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        elem = new int[10];
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        int sz = array.length;
        for(int i = 0; i < sz; i++){
            elem[i] = array[i];
        }
        usedSize = sz;
        for(int i = (usedSize - 1 - 1) / 2; i >= 0; i--){
            shiftDown(i);
        }
    }

    /**
     *
     * @param parent 是每棵子树的根节点的下标
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int parent) {
        int child = parent * 2 + 1;
        while(child < usedSize){
            //寻找左右孩子中较大的
            if(child + 1 < usedSize){
                child = elem[child] > elem[child + 1] ? child : child + 1;
            }
            //如果孩子节点较大，则进行交换
            if(elem[child] > elem[parent]){
                swap(parent, child);
                parent = child;
                child = parent * 2 + 1;
            }else {
                break;
            }
        }
    }

    private void swap(int i, int j){
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize++] = val;
        shiftUp(usedSize - 1);
    }

    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0){
            if(elem[child] > elem[parent]){
                swap(child, parent);
                child = parent;
                parent = (child - 1) / 2;
            }else{
                break;
            }
        }
    }

    public boolean isFull() {
        return elem.length == usedSize;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0, usedSize - 1);
        usedSize--;
        shiftDown(0);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(usedSize == 0){
            System.out.println("队列为空");
            return -1;
        }
        return elem[0];
    }

    public static void main(String[] args) {
        PriorityQueue priorityQueue = new PriorityQueue();
        int[] arr = new int[]{14,26,35,4,2,27,57,88};
        priorityQueue.createHeap(arr);
        while(!priorityQueue.isEmpty()){
            System.out.println(priorityQueue.peekHeap());
            priorityQueue.pollHeap();
        }
    }
}